package com.baidu.ota.view;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.commonlib.interfaces.ErrorCode;
import com.baidu.commonlib.interfaces.IOtaAgent;
import com.baidu.ota.R;
import com.baidu.ota.interfaces.ISystemInfo;
import com.baidu.ota.presenter.ICheckPresenter;
import com.baidu.ota.presenter.IUpgradePresenter;
import com.baidu.ota.presenter.PresenterFactory;
import com.baidu.otasdk.ota.Constants;

/**
 * Created by wubeilong on 2018/3/16.
 * page view
 */

public class PageViewItem extends RelativeLayout implements ICheckView, IUpgradeView, ConfirmFragment.IConfirmListener {
    private static final String LOADING_TAG = "loading_fragment";
    private static final String CONFIRM_TAG = "confirm_fragment";
    private ICheckPresenter checkPresenter;
    private IUpgradePresenter upgradePresenter;

    private String pkgName = "";
    private int state = IUpgradePresenter.STATE_INIT;

    private Button button, btn_exit;
    private Activity activity;
    private ProgressBar progressBar;

    public PageViewItem(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void initData(Activity activity, ISystemInfo info, IOtaAgent agent, int otaType) {
        this.activity = activity;

        TextView textView = findViewById(R.id.tv_title);
        textView.setText(R.string.app_name);

        if (otaType == 0) {
            TextView tvVersion = findViewById(R.id.tv_version);
            String txt = info.getDeviceId() + "\n" + info.getVersion();
            tvVersion.setText(txt);
        }
        checkPresenter = PresenterFactory.get(agent, this, otaType == 0);
        upgradePresenter = PresenterFactory.get(this);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        button = findViewById(R.id.btn_check);
        btn_exit = findViewById(R.id.btn_exit);
        button.setOnClickListener(new OnClickListener());
        btn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });

        progressBar = findViewById(R.id.progressbar);
    }

    @Override
    public void onCheckFailResult(int code, String reason) {
        dismissFragment();
        Log.e(Constants.TAG, "check error:" + code + "," + reason);

        String txt = activity.getString(R.string.check_update_fail)+ ":" + code;
        if (code == ErrorCode.CHECK_NO_UPDATE) {
            txt = activity.getString(R.string.no_update);
        } else if (code == ErrorCode.CHECK_NET_ERROR) {
            txt =activity.getString(R.string.no_network);
        }
        Toast.makeText(getContext(), txt, Toast.LENGTH_SHORT).show();
        button.setEnabled(true);

    }

    @Override
    public void onCheckSuccessResult(String pkgName, String info, String version) {
        this.pkgName = pkgName;
        Log.w(Constants.TAG, "check success");

        button.setEnabled(true);

        ConfirmFragment.setListener(this);
        ConfirmFragment dialog = new ConfirmFragment();
        Bundle bundle = new Bundle();
        bundle.putString("info", info);
        bundle.putString("version", version);
        dialog.setArguments(bundle);
        dialog.setCancelable(false);
        dialog.show(activity.getFragmentManager(), CONFIRM_TAG);

        dismissFragment();
    }

    @Override
    public void showProgressText(String txt) {
        Bundle bundle = new Bundle();
        bundle.putString("txt", txt);
        Fragment fragment = new LoadingFragment();
        fragment.setArguments(bundle);

        activity.getFragmentManager().beginTransaction()
                .add(R.id.container, fragment, LOADING_TAG)
                .commit();
    }

    private void dismissFragment() {
        Fragment fragment = activity.getFragmentManager().findFragmentByTag(LOADING_TAG);
        if (fragment != null) {
            activity.getFragmentManager().beginTransaction().remove(fragment).commit();
        }
    }

    @Override
    public void onConfirm(boolean yes) {
        if (yes) {
            upgradePresenter.download(pkgName);
        }
    }

    @Override
    public void onStateChanged(int state) {
        Log.w(Constants.TAG, "stateChange old=" + this.state + ",new=" + state);
        this.state = state;

        dismissFragment();
    }

    @Override
    public void onDownloadProgress(final int progress) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                button.setVisibility(INVISIBLE);
                btn_exit.setVisibility(INVISIBLE);
                progressBar.setVisibility(VISIBLE);
                progressBar.setProgress(progress);
            }
        });

    }

    @Override
    public void onDownloadFail(final int code, final String reason) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e(Constants.TAG, "download error:" + code + "," + reason);
                state = IUpgradePresenter.STATE_INIT;

                button.setEnabled(true);
                button.setText(R.string.retry);
                button.setVisibility(VISIBLE);
                btn_exit.setVisibility(VISIBLE);
                progressBar.setVisibility(INVISIBLE);
                progressBar.setProgress(0);
                progressBar.setSecondaryProgress(0);

                Toast.makeText(getContext(), "下载失败:" + code, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onDownloadPaused() {
        // ignore
    }

    @Override
    public void onDownloadSuccess() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                button.setVisibility(INVISIBLE);
                progressBar.setVisibility(VISIBLE);
                progressBar.setProgress(100);
                upgradePresenter.upgrade(pkgName);
            }
        });
    }

    @Override
    public void onUpgradeProgress(final int progress) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setSecondaryProgress(progress
                );

                Log.e("progress", "upgrade:" + progress);
            }
        });

    }

    @Override
    public void onUpgradeWriteDone() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setSecondaryProgress(100);
                Log.e("progress", "write done");
            }
        });


    }

    @Override
    public void onUpgradeFail(final int code, String reason) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                button.setEnabled(true);
                button.setText(R.string.retry);
                button.setVisibility(VISIBLE);

                progressBar.setVisibility(INVISIBLE);
                progressBar.setSecondaryProgress(0);
                progressBar.setProgress(0);

                Toast.makeText(getContext(), R.string.upgrade_fail + ":" + code, Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onUpgradeSuccess() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), R.string.upgrade_success, Toast.LENGTH_SHORT).show();

                button.setEnabled(true);
                button.setText(R.string.check_update);
                button.setVisibility(VISIBLE);
                progressBar.setVisibility(INVISIBLE);
                progressBar.setProgress(0);
                progressBar.setSecondaryProgress(0);
            }
        });

    }

    private class OnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int batteryPct = getBatteryPercentage();
            Log.d("PageViewItem", "onClick: " + batteryPct);
            if (batteryPct < 20) {
                Toast.makeText(activity, R.string.low_battery_warning, Toast.LENGTH_SHORT).show();
                return;
            }
            if (state == IUpgradePresenter.STATE_INIT || state == IUpgradePresenter.STATE_UPGRADE_SUCCESS) {
                checkPresenter.checkUpdate();
            } else {
                upgradePresenter.download(pkgName);
            }
            v.setEnabled(false);
        }
    }

    public int getBatteryPercentage() {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = activity.registerReceiver(null, ifilter);

        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

        if (level == -1 || scale == -1) {
            return 0;
        }

        float batteryPct = (level / (float) scale) * 100;
        return (int) batteryPct;
    }
}